<template>
  <div>
    <van-nav-bar
      title="咨询报告"
      left-text="返回"
      left-arrow
      :right-text="Text"
      fixed
      @click-left="handleBack"
      @click-right="handleSubmit"
    />
    <div class="reserve-view">
      <van-cell-group inset>
        <van-cell title="咨询师" :value="query.counselorName" />
        <van-cell title="咨询人" :value="query.userName" />
        <van-cell title="预约日期" :value="query.date" />
        <van-cell title="开始时间" :value="query.startTime" />
        <van-cell title="结束时间" :value="query.endTime" />
      </van-cell-group>
      <van-cell-group inset>
        <van-form ref="submit" @submit="onSubmit">
          <van-field
            v-model="serviceForm.complaint"
            rows="2"
            autosize
            label="咨询主诉"
            type="textarea"
            clearable="true"
            placeholder="请输入..."
            :disabled="fieldDisabled.complaintDisabled"
            :rules="[{ required: true, message: '请填写咨询主诉' }]"
          />
          <van-field
            v-model="serviceForm.content"
            rows="2"
            autosize
            label="咨询内容"
            type="textarea"
            :clearable="true"
            placeholder="请输入咨询内容"
            :disabled="fieldDisabled.contentDisabled"
            :rules="[{ required: true, message: '请填写咨询内容' }]"
          />
          <van-field
            v-model="serviceForm.nextTime"
            is-link
            readonly
            name="calendar"
            label="下次预约时间"
            placeholder="点击选择日期"
            :disabled="fieldDisabled.nextTimeDisabled"
            :rules="[{ required: true, message: '请选择日期' }]"
            @click="showCalendar = true"
          />
          <van-calendar v-model:show="showCalendar" @confirm="onConfirm" />
        </van-form>
        <van-form>
          <van-field
            v-model="userForm.opinion"
            rows="2"
            autosize
            label="意见"
            type="textarea"
            :required="true"
            :clearable="true"
            placeholder="请输入意见"
            :disabled="userDisabled.opinionDisabled"
            :rules="[{ required: true, message: '请填写意见' }]"
          />
          <van-field
            class="rate"
            :disabled="userDisabled.understandDisabled"
            name="rate"
            :required="true"
            label="我觉得咨询师可以理解到我"
            :rules="[{ required: true, message: '请评分' }]"
          >
            <template #input>
              <van-rate
                v-model="userForm.grasp"
                :disabled="userDisabled.understandDisabled"
              />
            </template>
          </van-field>
          <van-field
            class="rate"
            :disabled="userDisabled.helpDisabled"
            name="rate"
            :required="true"
            label="我觉得咨询师可以帮助到我"
            :rules="[{ required: true, message: '请评分' }]"
          >
            <template #input>
              <van-rate
                v-model="userForm.assist"
                :disabled="userDisabled.helpDisabled"
              />
            </template>
          </van-field>
          <van-field
            class="rate"
            :disabled="userDisabled.satisfactionDisabled"
            name="rate"
            :required="true"
            label="我觉得对咨询感到满意"
            :rules="[{ required: true, message: '请评分' }]"
          >
            <template #input>
              <van-rate
                v-model="userForm.satisfied"
                :disabled="userDisabled.satisfactionDisabled"
              />
            </template>
          </van-field>
        </van-form>
      </van-cell-group>
      <van-cell-group inset> </van-cell-group>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Toast } from 'vant'
import { useStore } from '/@/store'
import { submitServiceReport, submitServiceFeedback } from '../api'
import { ServiceForm, UserForm } from '../types'

export default defineComponent({
  setup() {
    const { query } = useRoute()
    const router = useRouter()
    let serviceForm = reactive<ServiceForm>({
      content: '',
      complaint: '',
      nextTime: '',
    })

    let userForm = reactive<UserForm>({
      assist: 0,
      satisfied: 0,
      grasp: 0,
      opinion: '',
      advisoryRecordsId: '',
    })

    const showCalendar = ref(false)
    const onConfirm = (date: any) => {
      if (fieldDisabled.dateDisabled || query.id) {
        Toast('无法修改当前时间')
        return
      }
      serviceForm.nextTime = `${date.getFullYear()}-${
        date.getMonth() + 1 < 10
          ? '0' + (date.getMonth() + 1)
          : date.getMonth() + 1
      }-${date.getDate() < 10 ? '0' + date.getDate() : date.getDate()}`
      showCalendar.value = false
    }

    const { fieldDisabled, userDisabled, handleSubmit, user, Text } = useReport(
      serviceForm,
      userForm,
      query
    )

    return {
      handleBack() {
        if (user.postName !== '心理专家') {
          router.push({
            name: 'consult',
          })
          return
        }
        if (query.id) {
          router.push({
            name: 'RecordsConsult',
          })
        } else {
          router.push({
            name: 'NotesOrder',
          })
        }
      },
      query,
      serviceForm,
      userForm,
      onConfirm,
      showCalendar,
      handleSubmit,
      fieldDisabled,
      userDisabled,
      user,
      onSubmit(val: any) {
        console.log(val)
      },
      Text,
    }
  },
})

function useReport(
  serviceForm: ServiceForm,
  userForm: UserForm,
  query: Record<string, any>
) {
  let fieldDisabled: Record<string, boolean> = reactive({
    complaintDisabled: false,
    contentDisabled: false,
    nextTimeDisabled: false,
  })

  let userDisabled: Record<string, boolean> = reactive({
    opinionDisabled: false,
    helpDisabled: false,
    understandDisabled: false,
    satisfactionDisabled: false,
  })
  const router = useRouter()
  const { state } = useStore()
  let user = reactive({ ...state.userInfo })
  //假如有咨询记录id禁用咨询师生成功能
  if (query.id) {
    userForm.advisoryRecordsId = query.id

    let advisoryReportEntityList = JSON.parse(query.advisoryReportEntityList)
    let advisoryFeedbackEntityList = JSON.parse(
      query.advisoryFeedbackEntityList
    )
    for (let i in fieldDisabled) {
      fieldDisabled[i] = true
    }
    for (let j in serviceForm) {
      serviceForm[j] = advisoryReportEntityList[0][j]
    }
    if (advisoryFeedbackEntityList.length > 0) {
      for (let z in userForm) {
        userForm[z] = advisoryFeedbackEntityList[0][z]
      }
      for (let x in userDisabled) {
        userDisabled[x] = true
      }
    }
  }

  watch(
    () => user,
    (val) => {
      if (user.postName && user?.postName === '心理专家') {
        for (let i in userDisabled) {
          userDisabled[i] = true
        }
      } else {
        for (let i in fieldDisabled) {
          fieldDisabled[i] = true
        }
      }
    },
    {
      immediate: true,
    }
  )

  const handleSubmit = () => {
    if (user.postName && user?.postName === '心理专家') {
      if (query.id) {
        Toast('当前无法修改！')
        return
      }
      let isRules = Object.values(serviceForm).every((item) => item.length > 0)
      if (!isRules) {
        Toast('请填写完整所需内容！')
        return
      }
      let data = reactive({
        appointmentReceiveId: query?.orderId,
        advisoryReportEntity: serviceForm,
      })

      submitServiceReport(data).then((res) => {
        Toast('咨询报告生成成功！')
        router.push({
          name: 'NotesOrder',
        })
      })
    } else {
      let advisoryFeedbackEntityList = JSON.parse(
        query.advisoryFeedbackEntityList
      )
      if (advisoryFeedbackEntityList.length > 0) {
        Toast('已反馈完成，现无须反馈！')
        return
      }
      let isRules = Object.values(userForm).every(
        (item) => item.length > 0 || item > 0
      )
      if (!isRules) {
        Toast('请填写完整反馈内容！')
        return
      }
      submitServiceFeedback(userForm).then((res) => {
        Toast('反馈成功！')
        router.push({
          name: 'consult',
        })
      })
    }
  }

  return {
    fieldDisabled,
    userDisabled,
    handleSubmit,
    user,
    Text: computed(() => {
      return user.postName == '心理专家' ? '生成' : '反馈'
    }),
  }
}
</script>

<style lang="less" scoped>
.reserve-view {
  margin-top: 55px;
  padding-bottom: 55px;

  .rate {
    /deep/.van-field__label {
      width: 180px;
    }
  }
}
</style>
